package com.nothing.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.nothing.config.StageManager;
import com.nothing.domain.UserFaceGroup;
import com.nothing.domain.UserFaceInfo;
import com.nothing.service.UserFaceInfoService;
import com.nothing.view.FxmlView;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.PasswordField;
import javafx.scene.control.RadioButton;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Callback;

/**
 * 人脸管理
 * @author shíQíang㊚
 */

@Controller
public class FaceController implements Initializable {

	@FXML
	private ImageView showImg;

	@FXML
	private Label userId;

	@FXML
	private Button btnGoBack;

	@FXML
	private Button btnGoCheck;

	@FXML
	private TextField name;

	@FXML
	private RadioButton rbMale;

	@FXML
	private ToggleGroup gender;

	@FXML
	private RadioButton rbFemale;

	@FXML
	private TextField age;

	@FXML
	private PasswordField password;

	@FXML
	private Button selFile;

	@FXML
	private Button saveUser;

	@FXML
	private TableView<UserFaceInfo> userTable;

	@FXML
	private TableColumn<UserFaceInfo, Long> colUserId;

	@FXML
	private TableColumn<UserFaceInfo, String> colName;

	@FXML
	private TableColumn<UserFaceInfo, String> colAge;

	@FXML
	private TableColumn<UserFaceInfo, String> colGender;

	@FXML
	private TableColumn<UserFaceInfo, Boolean> colEdit;

	@FXML
	private ChoiceBox<UserFaceGroup> groupOptions;

	@FXML
	private MenuItem deleteUsers;

	@Lazy
	@Autowired
	private StageManager stageManager;

	@Autowired
	private UserFaceInfoService userFaceInfoService;

	private ObservableList<UserFaceInfo> userList = FXCollections.observableArrayList();
	// private ObservableList<String> roles = FXCollections.observableArrayList
	// ("Admin", "User");

	@FXML
	private void exit(ActionEvent event) {
		Platform.exit();
	}

	/**
	 * Logout and go to the login page
	 */
	@FXML
	private void goBack(ActionEvent event) throws IOException {
		stageManager.switchScene(FxmlView.USER);
	}

	@FXML
	private void goCheckFace(ActionEvent event) throws IOException {
		stageManager.switchScene(FxmlView.CHECK);
	}

	@FXML
	private void toCam(ActionEvent event) throws IOException {
		stageManager.switchScene(FxmlView.IPCAM);
	}

	@FXML
	void reset(ActionEvent event) {
		clearFields();
	}

	@FXML
	void selFile(ActionEvent event) {
		FileChooser fileChooser = new FileChooser();
		fileChooser.setTitle("图片查看");
		fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
		fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("All Images", "*.*"),
				new FileChooser.ExtensionFilter("JPG", "*.jpg"), new FileChooser.ExtensionFilter("GIF", "*.gif"),
				new FileChooser.ExtensionFilter("BMP", "*.bmp"), new FileChooser.ExtensionFilter("PNG", "*.png"));
		Stage selectFile = new Stage();
		File file = fileChooser.showOpenDialog(selectFile);
		if (file == null)
			return;
		showImg.setImage(new Image("file:" + file.getAbsolutePath()));
	}

	@FXML
	private void saveUser(ActionEvent event) {

		try {
			BufferedImage img = SwingFXUtils.fromFXImage(showImg.getImage(), null);

			userFaceInfoService.saveFace(img, name.getText(),
					groupOptions.getSelectionModel().getSelectedItem().getId(), rbMale.isSelected() ? 1 : 0,
					Integer.valueOf(age.getText()));

		} catch (Exception e) {
			e.printStackTrace(); 
		}

		clearFields();
		loadUserDetails();
	}

	public String getName() {
		return name.getText();
	}

	public void setName(TextField name) {
		this.name = name;
	}

	public TextField getAge() {
		return age;
	}

	public void setAge(TextField age) {
		this.age = age;
	}

	@FXML
	private void deleteUsers(ActionEvent event) {
		List<UserFaceInfo> users = userTable.getSelectionModel().getSelectedItems();

		Alert alert = new Alert(AlertType.CONFIRMATION);
		alert.setTitle("确认框");
		alert.setHeaderText(null);
		alert.setContentText("确定删除当前用户吗？");
		Optional<ButtonType> action = alert.showAndWait();

		if (action.get() == ButtonType.OK)
			userFaceInfoService.deleteInBatch(users);

		loadUserDetails();
	}

	private void clearFields() {
		userId.setText(null);
		name.clear();
		rbMale.setSelected(true);
		rbFemale.setSelected(false);
		age.clear();
	}

	public String getGender() {
		return rbMale.isSelected() ? "1" : "0";
	}

	public String getPassword() {
		return password.getText();
	}

	@Override
	public void initialize(URL location, ResourceBundle resources) { 
		 
		ObservableList<UserFaceGroup> options = FXCollections.observableArrayList(
				UserFaceGroup.builder().id(1L).name("特殊人").build(),
				UserFaceGroup.builder().id(2L).name("普通人").build());
		 
		groupOptions.setItems(options);

		userTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

		setColumnProperties();
 
		loadUserDetails();
	}

	/*
	 * Set All userTable column properties
	 */
	private void setColumnProperties() {

		colUserId.setCellValueFactory(new PropertyValueFactory<>("id"));
		colName.setCellValueFactory(new PropertyValueFactory<>("name"));
		colGender.setCellValueFactory(new PropertyValueFactory<>("gender"));
		colAge.setCellValueFactory(new PropertyValueFactory<>("age"));
		// colEdit.setCellFactory (cellFactory);
	}

	Callback<TableColumn<UserFaceInfo, Boolean>, TableCell<UserFaceInfo, Boolean>> cellFactory = new Callback<TableColumn<UserFaceInfo, Boolean>, TableCell<UserFaceInfo, Boolean>>() {

		@Override
		public TableCell<UserFaceInfo, Boolean> call(final TableColumn<UserFaceInfo, Boolean> param) {
			final TableCell<UserFaceInfo, Boolean> cell = new TableCell<UserFaceInfo, Boolean>() {

				Image imgEdit = new Image(getClass().getResourceAsStream("/images/edit.png"));
				final Button btnEdit = new Button();

				@Override
				public void updateItem(Boolean check, boolean empty) {
					super.updateItem(check, empty);
					if (empty) {
						setGraphic(null);
						setText(null);
					} else {
						btnEdit.setOnAction(e -> {
							UserFaceInfo user = getTableView().getItems().get(getIndex());
							updateUser(user);
						});

						btnEdit.setStyle("-fx-background-color: transparent;");
						ImageView iv = new ImageView();
						iv.setImage(imgEdit);
						iv.setPreserveRatio(true);
						iv.setSmooth(true);
						iv.setCache(true);
						btnEdit.setGraphic(iv);

						setGraphic(btnEdit);
						setAlignment(Pos.CENTER);
						setText(null);
					}
				}

				private void updateUser(UserFaceInfo user) {
					userId.setText(Long.toString(user.getId()));
					name.setText(user.getName());
					if (user.getGender() == 1)
						rbMale.setSelected(true);
					else
						rbFemale.setSelected(true);
				}
			};
			return cell;
		}
	};

	private void loadUserDetails() {
		userList.clear();
		userList.addAll(userFaceInfoService.selectPage(new Page<UserFaceInfo>()).getRecords());
		userTable.setItems(userList);
	}
}
